package com.qinglei.recoup.hmp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.utils.DateTimeUtils;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.hmp.domain.HmpUserBindDevice;
import com.qinglei.recoup.hmp.pojo.vo.*;
import com.qinglei.recoup.hmp.pojo.vo.healthReport.*;
import com.qinglei.recoup.hmp.service.HmpHealthReportService;
import com.qinglei.recoup.hmp.service.HmpUserBindDeviceService;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.pojo.OutBedDurationMoreVO;
import com.qinglei.recoup.system.pojo.OutBedNumMoreVO;
import com.qinglei.recoup.system.pojo.TurnOverMoreNum;
import com.qinglei.recoup.system.pojo.*;
import com.qinglei.recoup.system.service.BedHealthDailyStatisticsService;
import com.qinglei.recoup.system.service.RadarBedService;
import com.qinglei.recoup.system.service.RadarService;
import com.qinglei.recoup.system.util.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>小程序睡眠报告相关接口</p>
 *
 * @author shiyupeng
 * @date 2022/1/15
 */
@Service
@Slf4j
public class HmpHealthReportServiceImpl implements HmpHealthReportService {

    @Resource
    private BedHealthDailyStatisticsService bedHealthDailyStatisticsService;

    @Resource
    private HmpUserBindDeviceService hmpUserBindDeviceService;

    @Resource
    private RadarService radarService;

    @Resource
    private RadarBedService radarBedService;

    /**
     * 获取单日睡眠报告基础数据接口
     *
     * @param userId
     * @param sn
     * @param date
     * @return
     */
    @Override
    public CommonRes<HmpSleepReportBasicVO> getSleepReportBasicOneDay(Long userId, String sn, String date, Integer badId) {
//        HmpUserBindDevice hmpUserBindDevice = hmpUserBindDeviceService.getOne(Wrappers.<HmpUserBindDevice>lambdaQuery()
//                .eq(HmpUserBindDevice::getUserId, userId).eq(HmpUserBindDevice::getDeviceSn, sn));
//        if (hmpUserBindDevice == null) {
//            return CommonRes.failed("用户未绑定该设备");
//        }

        BedHealthShareParam bedHealthShareParam = new BedHealthShareParam();
        // 设置起止时间条件
        bedHealthShareParam.setBedId(badId);
        bedHealthShareParam.setStartDate(date);
        bedHealthShareParam.setEndDate(date);
        BedHealthDailyStatistics bedHealthDailyStatistics = bedHealthDailyStatisticsService.selectBedHealthDailyStatistics(bedHealthShareParam);
        HmpSleepReportBasicVO hmpSleepReportBasicVO = new HmpSleepReportBasicVO();
        hmpSleepReportBasicVO.setSleepDuration(bedHealthDailyStatistics.getSleepDuration());
        hmpSleepReportBasicVO.setResultFlag(bedHealthDailyStatistics.getResultFlag());
        hmpSleepReportBasicVO.setSleepLenValidMin(bedHealthDailyStatistics.getSleepLenValidMin());
        log.info("getSleepReportBasicOneDay,bedHealthDailyStatistics:{}", JsonUtils.objectToJson(bedHealthDailyStatistics));
        if (bedHealthDailyStatistics != null && bedHealthDailyStatistics.getResultFlag() == 0) {
            HealthDetailParam param = new HealthDetailParam();
            param.setBedId(badId);
            param.setDate(LocalDate.parse(date));
            SleepReportVO sleepReportOne = bedHealthDailyStatisticsService.getSleepReportOneV1(param);
            if (sleepReportOne == null) {
                return CommonRes.failed("缺少健康报告数据");
            }
            // 查询有统计报告的第一天
            BedHealthDailyStatistics firstDate = bedHealthDailyStatisticsService.getOne(Wrappers.<BedHealthDailyStatistics>lambdaQuery()
                    .eq(BedHealthDailyStatistics::getBedId, sleepReportOne.getBedId())
                    .last("order by statistics_date asc limit 1"));

            if (!Objects.isNull(firstDate)) {
                hmpSleepReportBasicVO.setFirstDate(firstDate.getStatisticsDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            }
            hmpSleepReportBasicVO.setBedId(sleepReportOne.getBedId());
            hmpSleepReportBasicVO.setBedName(sleepReportOne.getBedName());
            hmpSleepReportBasicVO.setStatisticsDate(sleepReportOne.getStatisticsDate());
            hmpSleepReportBasicVO.setScore(sleepReportOne.getScore());
            if (sleepReportOne.getScore() < 60) {
                hmpSleepReportBasicVO.setComment("一般");
            } else if (sleepReportOne.getScore() >= 60 && sleepReportOne.getScore() < 80) {
                hmpSleepReportBasicVO.setComment("良好");
            } else {
                hmpSleepReportBasicVO.setComment("优秀");
            }
            hmpSleepReportBasicVO.setProportion(sleepReportOne.getProportion() == null ? 0 : Integer.parseInt(sleepReportOne.getProportion()));
            hmpSleepReportBasicVO.setPositiveResult(sleepReportOne.getPositiveResult());
            hmpSleepReportBasicVO.setGetBedTime(sleepReportOne.getGetBedIdx());
            hmpSleepReportBasicVO.setLeaveBedTime(sleepReportOne.getLeaveBedIdx());
            hmpSleepReportBasicVO.setBeginTime(sleepReportOne.getSleepStIdx());
            hmpSleepReportBasicVO.setEndTime(sleepReportOne.getSleepEdIdx());

            HealthStatusCommentVO healthStatusCommentVO = new HealthStatusCommentVO();
            healthStatusCommentVO.setAHI(sleepReportOne.getAhi());
            healthStatusCommentVO.setSleepDuration(sleepReportOne.getSleepDuration());
            healthStatusCommentVO.setOutBedDuration(sleepReportOne.getOutBedDuration());
            healthStatusCommentVO.setOutBedNum(sleepReportOne.getOutBedNum());
            healthStatusCommentVO.setTurnOverNum(sleepReportOne.getTurnOverNum());
            healthStatusCommentVO.setFall(sleepReportOne.getFall());
            healthStatusCommentVO.setMorale(sleepReportOne.getMorale());
            healthStatusCommentVO.setVitality(sleepReportOne.getVitality());
            // 获取负面报告列表
            List<NegativeItemVO> negativeList = HealthStatusComment.getNegativeCommentList(healthStatusCommentVO);
            hmpSleepReportBasicVO.setNegativeList(negativeList);

            // 获取睡眠详情列表
            SleepInfoCommentDTO sleepInfoCommentDTO = new SleepInfoCommentDTO();
            BeanUtils.copyProperties(sleepReportOne, sleepInfoCommentDTO);
            List<SleepItemVO> sleepInfoList = HealthStatusComment.getSleepInfoList(sleepInfoCommentDTO);
            //睡眠效率的兼容
            if (null != bedHealthDailyStatistics.getSleepEff() && !CollectionUtils.isEmpty(sleepInfoList)) {
                for (SleepItemVO sleepItemVO : sleepInfoList) {
                    if ("睡眠效率".equals(sleepItemVO.getName())) {
                        if (bedHealthDailyStatistics.getSleepEff() < 80) {
                            sleepItemVO.setComment("偏低");
                        } else {
                            sleepItemVO.setComment("正常");
                        }
                        sleepItemVO.setValue(bedHealthDailyStatistics.getSleepEff() + "%");
                    }
                }
            }
            hmpSleepReportBasicVO.setSleepInfo(sleepInfoList);
            hmpSleepReportBasicVO.setHealthStatus(healthStatusCommentVO);
            hmpSleepReportBasicVO.setGradeMap(sleepReportOne.getGradeMap());
            return CommonRes.ok(hmpSleepReportBasicVO);
        } else {
            return CommonRes.ok(null, bedHealthDailyStatistics.getResultFlagStr());
        }
    }

    /**
     * 获取单日睡眠报告图表数据接口
     *
     * @param userId
     * @param sn
     * @param date
     * @return
     */
    @Override
    public CommonRes<HmpSleepReportChartVO> getSleepReportChartOneDay(Long userId, String sn, String date, Integer badId) {
//        HmpUserBindDevice hmpUserBindDevice = hmpUserBindDeviceService.getOne(Wrappers.<HmpUserBindDevice>lambdaQuery()
//                .eq(HmpUserBindDevice::getUserId, userId).eq(HmpUserBindDevice::getDeviceSn, sn));
//        if (hmpUserBindDevice == null) {
//            return CommonRes.failed("用户未绑定该设备");
//        }

        BedHealthShareParam bedHealthShareParam = new BedHealthShareParam();
        // 设置起止时间条件
        bedHealthShareParam.setBedId(badId);
        bedHealthShareParam.setStartDate(date);
        bedHealthShareParam.setEndDate(date);
        BedHealthDailyStatistics bedHealthDailyStatistics = bedHealthDailyStatisticsService.selectBedHealthDailyStatistics(bedHealthShareParam);

        if (bedHealthDailyStatistics != null && bedHealthDailyStatistics.getResultFlag() == 0) {
            HealthDetailParam param = new HealthDetailParam();
            param.setBedId(badId);
            param.setDate(LocalDate.parse(date));
            SleepReportVO sleepReportOne = bedHealthDailyStatisticsService.getSleepReportOneV1(param);
            if (sleepReportOne == null) {
                return CommonRes.failed("缺少健康报告数据");
            }
            BedHealthBreathDailyData healthReportV1 = bedHealthDailyStatisticsService.getHealthReportV1(param);
            if (healthReportV1 == null) {
                return CommonRes.failed("缺少呼吸报告数据");
            }
            HmpSleepReportChartVO hmpSleepReportChartVO = new HmpSleepReportChartVO();
            hmpSleepReportChartVO.setBedId(sleepReportOne.getBedId());
            hmpSleepReportChartVO.setBedName(sleepReportOne.getBedName());
            hmpSleepReportChartVO.setStatisticsDate(sleepReportOne.getStatisticsDate());
            hmpSleepReportChartVO.setMinutes(sleepReportOne.getMinutes());
            hmpSleepReportChartVO.setCutStIdx(sleepReportOne.getCutStIdx());
            hmpSleepReportChartVO.setCutEdIdx(sleepReportOne.getCutEdIdx());

            // 呼吸数据
            BHItemVO breathData = new BHItemVO();
            breathData.setMin((int) Math.round(sleepReportOne.getBreathMin()));
            breathData.setMax((int) Math.round(sleepReportOne.getBreathMax()));
            breathData.setAvg((int) Math.round(sleepReportOne.getBreathAvg()));
            //做个兼容
            if (null != bedHealthDailyStatistics.getBreathMin()) {
                breathData.setMin(bedHealthDailyStatistics.getBreathMin());
            }
            if (null != bedHealthDailyStatistics.getBreathMax()) {
                breathData.setMax(bedHealthDailyStatistics.getBreathMax());
            }
            if (null != bedHealthDailyStatistics.getBreathMean()) {
                breathData.setAvg(bedHealthDailyStatistics.getBreathMean());
            }
            if (breathData.getAvg() < 8) {
                breathData.setAvgComment("偏低");
            } else if (breathData.getAvg() > 24) {
                breathData.setAvgComment("偏高");
            } else {
                breathData.setAvgComment("正常");
            }
            breathData.setData(sleepReportOne.getBreathPhaseData());
            hmpSleepReportChartVO.setBreathData(breathData);

            // 心跳数据
            BHItemVO heartData = new BHItemVO();
            heartData.setMin((int) Math.round(sleepReportOne.getHeartMin()));
            heartData.setMax((int) Math.round(sleepReportOne.getHeartMax()));
            heartData.setAvg((int) Math.round(sleepReportOne.getHeartAvg()));
            //心跳兼容
            if (null != bedHealthDailyStatistics.getHeartMin()) {
                heartData.setMin(bedHealthDailyStatistics.getHeartMin());
            }
            if (null != bedHealthDailyStatistics.getHeartMax()) {
                heartData.setMax(bedHealthDailyStatistics.getHeartMax());
            }
            if (null != bedHealthDailyStatistics.getHeartMean()) {
                heartData.setAvg(bedHealthDailyStatistics.getHeartMean());
            }
            if (heartData.getAvg() < 45) {
                heartData.setAvgComment("偏低");
            } else if (heartData.getAvg() > 90) {
                heartData.setAvgComment("偏高");
            } else {
                heartData.setAvgComment("正常");
            }
            heartData.setData(sleepReportOne.getHeartPhaseData());
            hmpSleepReportChartVO.setHeartData(heartData);

            // 睡眠数据
            hmpSleepReportChartVO.setSleepData(sleepReportOne.getSleepData());

            // 体动信息
            NumDataItemVO numDataItemVO = new NumDataItemVO();
            numDataItemVO.setNum(sleepReportOne.getTurnOverNum());
            numDataItemVO.setData(sleepReportOne.getTurnOverData());
            hmpSleepReportChartVO.setTurnOverData(numDataItemVO);

            // 呼吸事件列表
            List<BreathEventVO> healthReport = new ArrayList<>();
            BreathEventVO breathEventVO = new BreathEventVO();
            breathEventVO.setName("呼吸暂停");
            breathEventVO.setValue(healthReportV1.getApneaTotalNumber());
            breathEventVO.setAverageDuration(getSecondDurationText(Math.round(healthReportV1.getApneaAverageTime().intValue())));
            healthReport.add(breathEventVO);
            BreathEventVO breathEventVOAHI = new BreathEventVO();
            breathEventVOAHI.setName("AHI");
            breathEventVOAHI.setValue(String.valueOf(healthReportV1.getAhi()));
            healthReport.add(breathEventVOAHI);
            hmpSleepReportChartVO.setHealthReport(healthReport);

            String riskSituation = HealthStatusComment.getCommentByAhi(healthReportV1.getAhi());
            hmpSleepReportChartVO.setRiskSituation(riskSituation);
            hmpSleepReportChartVO.setFlagBreathReport(healthReportV1.getFlagBreathReport());
//            hmpSleepReportChartVO.setAhiComment("呼吸紊乱指数是医学上用于确定呼吸紊乱严重程度的重要指标。呼吸暂停医学评级标准：AHI<5 为健康，5≤AHI<15 疑似低风险，15≤AHI<30 疑似中风险，AHI≥30 疑似高风险");
            hmpSleepReportChartVO.setAhiComment("AHI是医学上用于确定呼吸暂停严重程度的重要指标，AHI医学评级标准：AHI<5 为健康，5≤AHI<15 疑似低风险，15≤AHI<30 疑似中风险，AHI≥30 疑似高风险");

            // AHI数据
            NumDataItemVO ahiData = new NumDataItemVO();
            ahiData.setNum(healthReportV1.getApneaTotalNumber());
            if (StringUtils.isNotEmpty(healthReportV1.getApneaFrequencyStr())) {
                ahiData.setData(JsonUtils.jsonToList(healthReportV1.getApneaFrequencyStr(), Integer.class));
            }
            hmpSleepReportChartVO.setAhiData(ahiData);

            // abnData
            AbnItemVO abnData = new AbnItemVO();
            abnData.setPowThr1(sleepReportOne.getPowThr1());
            abnData.setBreathPhaseSection(sleepReportOne.getBreathPhaseSection());
            abnData.setHrrpSection(sleepReportOne.getHrrpSection());
            hmpSleepReportChartVO.setAbnData(abnData);
            //呼吸事件
            hmpSleepReportChartVO.setSliceTimeStr(healthReportV1.getSliceTimeStr());
            hmpSleepReportChartVO.setTimeStampMin(healthReportV1.getTimeStampMin());
            hmpSleepReportChartVO.setFigOssUrl(healthReportV1.getFigOssUrl());
            return CommonRes.ok(hmpSleepReportChartVO);
        } else {
            return CommonRes.ok(null, bedHealthDailyStatistics.getResultFlagStr());
        }
    }

    /**
     * 获取多日睡眠报告数据接口
     *
     * @param userId
     * @param sn
     * @param startDateStr
     * @param endDateStr
     * @return
     */
    @Override
    public CommonRes<HmpSleepReportMoreVO> getSleepReportMoreDay(Long userId, String sn, String startDateStr, String endDateStr) {
        HmpUserBindDevice hmpUserBindDevice = hmpUserBindDeviceService.getOne(Wrappers.<HmpUserBindDevice>lambdaQuery()
                .eq(HmpUserBindDevice::getUserId, userId).eq(HmpUserBindDevice::getDeviceSn, sn));
        if (hmpUserBindDevice == null) {
            return CommonRes.failed("用户未绑定该设备");
        }
        LocalDate startDate = LocalDate.parse(startDateStr);
        LocalDate endDate = LocalDate.parse(endDateStr);

        log.debug("getSleepReportMoreDay call getReportMore4Hmp bedId:{},startDate:{},endDate:{}", hmpUserBindDevice.getBedId(), startDate, endDate);
        SleepReportMoreVO reportMore4Hmp = bedHealthDailyStatisticsService.getReportMore4Hmp(hmpUserBindDevice.getBedId(), startDate, endDate);
        log.debug("getSleepReportMoreDay call getReportMore4Hmp return:{}", reportMore4Hmp);
        if (reportMore4Hmp == null) {
            return CommonRes.failed("缺少健康报告数据");
        }
        HmpSleepReportMoreVO hmpSleepReportMoreVO = new HmpSleepReportMoreVO();
        hmpSleepReportMoreVO.setBedId(reportMore4Hmp.getBedId());
        hmpSleepReportMoreVO.setBedName(reportMore4Hmp.getBedName());
        hmpSleepReportMoreVO.setStatisticsDate(reportMore4Hmp.getStatisticsDate());
        int dayNum = Period.between(startDate, endDate).getDays() + 1;
        hmpSleepReportMoreVO.setDayNum(dayNum);
        hmpSleepReportMoreVO.setEndDate(endDate.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
        // 查询有统计报告的第一天
        BedHealthDailyStatistics firstDate = bedHealthDailyStatisticsService.getOne(Wrappers.<BedHealthDailyStatistics>lambdaQuery()
                .eq(BedHealthDailyStatistics::getBedId, reportMore4Hmp.getBedId())
                .last("order by statistics_date asc limit 1"));
        hmpSleepReportMoreVO.setFirstDate(firstDate.getStatisticsDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        Map<String, Object> resultMapSrc = reportMore4Hmp.getResultMap();
        ResultMapVO resultMap = new ResultMapVO();
        if (resultMapSrc.get("ahiAVG") != null) {
            resultMap.setAhiAVG((Double) resultMapSrc.get("ahiAVG"));
        }
        if (resultMapSrc.get("ahiX") != null) {
            resultMap.setAhiX((List<String>) resultMapSrc.get("ahiX"));
        }
        if (resultMapSrc.get("ahiy") != null) {
            resultMap.setAhiy((List<Double>) resultMapSrc.get("ahiy"));
        }

        if (resultMapSrc.get("scoreAVG") != null) {
            resultMap.setScoreAVG(((Double) resultMapSrc.get("scoreAVG")).intValue());
        }
        if (resultMapSrc.get("scoreX") != null) {
            resultMap.setScoreX((List<String>) resultMapSrc.get("scoreX"));
        }
        if (resultMapSrc.get("scoreY") != null) {
            resultMap.setScoreY((List<Double>) resultMapSrc.get("scoreY"));
        }

        if (resultMapSrc.get("moraleAVG") != null) {
            resultMap.setMoraleAVG(((Double) resultMapSrc.get("moraleAVG")).intValue());
        }
        if (resultMapSrc.get("moraleX") != null) {
            resultMap.setMoraleX((List<String>) resultMapSrc.get("moraleX"));
        }
        if (resultMapSrc.get("moraleY") != null) {
            resultMap.setMoraleY((List<Integer>) resultMapSrc.get("moraleY"));
        }

        if (resultMapSrc.get("fallAVG") != null) {
            resultMap.setFallAVG(((Double) resultMapSrc.get("fallAVG")).intValue());
        }
        if (resultMapSrc.get("fallX") != null) {
            resultMap.setFallX((List<String>) resultMapSrc.get("fallX"));
        }
        if (resultMapSrc.get("fallY") != null) {
            resultMap.setFallY((List<Integer>) resultMapSrc.get("fallY"));
        }

        if (resultMapSrc.get("vitalityAVG") != null) {
            resultMap.setVitalityAVG(((Double) resultMapSrc.get("vitalityAVG")).intValue());
        }
        if (resultMapSrc.get("vitalityX") != null) {
            resultMap.setVitalityX((List<String>) resultMapSrc.get("vitalityX"));
        }
        if (resultMapSrc.get("vitalityY") != null) {
            resultMap.setVitalityY((List<Integer>) resultMapSrc.get("vitalityY"));
        }
        hmpSleepReportMoreVO.setResultMap(resultMap);

        // sleepDurationChart
        SleepDurationChartVO sleepDurationChartVO = new SleepDurationChartVO();
        sleepDurationChartVO.setSleepSum(reportMore4Hmp.getSleepSum());
        sleepDurationChartVO.setSleepAvg(reportMore4Hmp.getSleepAvg());
        sleepDurationChartVO.setSleepMoreVOS(reportMore4Hmp.getSleepMoreVOS());
        hmpSleepReportMoreVO.setSleepDurationChart(sleepDurationChartVO);

        // 离床次数图表数据
        HmpChartDataVO<Integer> outBedNum = new HmpChartDataVO<>();
        List<OutBedNumMoreVO> outBedNumSrc = reportMore4Hmp.getOutBedNum();
        if (outBedNumSrc != null) {
            List<StatisticsDataItemVO<Integer>> data = new ArrayList<>();
            int sum = 0;
            int cnt = 0;
            for (OutBedNumMoreVO outBedNumMoreVO : outBedNumSrc) {
                StatisticsDataItemVO<Integer> item = new StatisticsDataItemVO<>();
                item.setStatisticsDate(outBedNumMoreVO.getStatisticsDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                item.setData(outBedNumMoreVO.getOutBedNum());
                data.add(item);
                if (outBedNumMoreVO.getOutBedNum() != null) {
                    sum += outBedNumMoreVO.getOutBedNum();
                    cnt++;
                }
            }
            outBedNum.setData(data);
            if (cnt > 0) {
                outBedNum.setAvg(Math.round(((float) sum) / cnt));
            } else {
                outBedNum.setAvg(0);
            }
            hmpSleepReportMoreVO.setOutBedNum(outBedNum);
        }

        // 离床时长图表数据
        HmpChartDataVO<Integer> outBedDuration = new HmpChartDataVO<>();
        List<OutBedDurationMoreVO> outBedDurationSrc = reportMore4Hmp.getOutBedDuration();
        if (outBedDurationSrc != null) {
            List<StatisticsDataItemVO<Integer>> data = new ArrayList<>();
            int sum = 0;
            int cnt = 0;
            for (OutBedDurationMoreVO outBedDurationMoreVO : outBedDurationSrc) {
                StatisticsDataItemVO<Integer> item = new StatisticsDataItemVO<>();
                item.setStatisticsDate(outBedDurationMoreVO.getStatisticsDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                item.setData(outBedDurationMoreVO.getOutBedMinute());
                item.setDuration(outBedDurationMoreVO.getOutBedDuration());
                data.add(item);
                if (outBedDurationMoreVO.getOutBedMinute() != null) {
                    sum += outBedDurationMoreVO.getOutBedMinute();
                    cnt++;
                }
            }
            outBedDuration.setData(data);
            if (cnt > 0) {
                outBedDuration.setAvg(Math.round(((float) sum) / cnt));
            } else {
                outBedDuration.setAvg(0);
            }
            hmpSleepReportMoreVO.setOutBedDuration(outBedDuration);
        }

        // 翻身图表数据
        HmpChartDataVO<Integer> turnOver = new HmpChartDataVO<>();
        List<TurnOverMoreNum> turnOverMoreNums = reportMore4Hmp.getTurnOverMoreNums();
        if (turnOverMoreNums != null) {
            List<StatisticsDataItemVO<Integer>> data = new ArrayList<>();
            for (TurnOverMoreNum turnOverMoreNum : turnOverMoreNums) {
                StatisticsDataItemVO<Integer> item = new StatisticsDataItemVO<>();
                item.setStatisticsDate(turnOverMoreNum.getStatisticsDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                item.setData(turnOverMoreNum.getTurnOverNum());
                data.add(item);
            }
            turnOver.setData(data);
            turnOver.setAvg((int) Math.round(reportMore4Hmp.getTurnOverMoreAvg()));
            hmpSleepReportMoreVO.setTurnOver(turnOver);
        }

        // breathRuleData
        HealthDetailParamV1 healthDetailParamV1 = new HealthDetailParamV1();
        healthDetailParamV1.setBedId(reportMore4Hmp.getBedId());
        healthDetailParamV1.setStartTime(startDate);
        healthDetailParamV1.setEndTime(endDate);
        Map<String, Object> healthReportV3 = (Map<String, Object>) bedHealthDailyStatisticsService.getHealthReportV3(healthDetailParamV1);
        if (healthReportV3 != null) {
            BreathRuleDataVO breathRuleData = new BreathRuleDataVO();
            breathRuleData.setMin((Integer) healthReportV3.get("breathDataMin"));
            breathRuleData.setMax((Integer) healthReportV3.get("breathDataMax"));
            breathRuleData.setAvg((int) ((long) healthReportV3.get("breathDataAvg")));
            breathRuleData.setBreathData(healthReportV3.get("breathData"));
            hmpSleepReportMoreVO.setBreathRuleData(breathRuleData);
        }

        // heartRuleData
        Map<String, Object> healthReportV2 = (Map<String, Object>) bedHealthDailyStatisticsService.getHealthReportV2(healthDetailParamV1);
        if (healthReportV2 != null) {
            HeartRuleDataVO heartRuleData = new HeartRuleDataVO();
            heartRuleData.setMin((Integer) healthReportV2.get("heartDataMin"));
            heartRuleData.setMax((Integer) healthReportV2.get("heartDataMax"));
            heartRuleData.setAvg((int) ((long) healthReportV2.get("heartDataAvg")));
            heartRuleData.setHeartData(healthReportV2.get("heartData"));
            hmpSleepReportMoreVO.setHeartRuleData(heartRuleData);

            // sleepRuleData
            hmpSleepReportMoreVO.setSleepRuleData(healthReportV2.get("sleepRule"));
        }

        // sleepSug
        if (dayNum > 7) {
            Object reportInterpretation = bedHealthDailyStatisticsService.getReportInterpretation(healthDetailParamV1);
            hmpSleepReportMoreVO.setSleepSug(reportInterpretation);
        }

        return CommonRes.ok(hmpSleepReportMoreVO);
    }

    /**
     * @param duration
     * @return
     */
    private static String getSecondDurationText(Integer duration) {
        Integer minute = duration / 60;
        Integer second = duration % 60;
        StringBuilder sb = new StringBuilder();
        if (minute > 0) {
            sb.append(minute);
            sb.append("分钟");
        }
        sb.append(second);
        sb.append("秒");
        return sb.toString();
    }

    @Override
    public CommonRes<HealthReportDayVo> getsleepReportOneDay(Long userId, String sn, String date, Integer sourceType) {
        Integer bedId = 0;
        if (null != sourceType && sourceType == 2) {
            //如果是小程序
            HmpUserBindDevice hmpUserBindDevice = hmpUserBindDeviceService.getOne(Wrappers.<HmpUserBindDevice>lambdaQuery()
                    .eq(HmpUserBindDevice::getUserId, userId).eq(HmpUserBindDevice::getDeviceSn, sn));
            if (hmpUserBindDevice == null) {
                return CommonRes.failed("用户未绑定该设备");
            }
            bedId = hmpUserBindDevice.getBedId();
        } else {
            Radar radar = radarService.getOne(new QueryWrapper<Radar>().lambda().eq(Radar::getSnCode, sn));
            if (Objects.isNull(radar)) {
                return CommonRes.failed("该设备号不存在");
            }
            RadarBed radarBed = radarBedService.getOne(new QueryWrapper<RadarBed>().lambda().eq(RadarBed::getRadarId, radar.getId()).eq(RadarBed::getIsDeleted, 0));
            if (Objects.isNull(radarBed)) {
                return CommonRes.failed("该设备号未绑定床位");
            }
            bedId = radarBed.getBedId();
        }
        return this.getSleepReportOneDayByBedId(userId, bedId, date);
    }

    @Override
    public CommonRes<HealthReportDayVo> getSleepReportOneDayByBedIdAndDate(Integer bedId, String date) {
        return getSleepReportOneDayByBedId(null, bedId, date);
    }

    public CommonRes<HealthReportDayVo> getSleepReportOneDayByBedId(Long userId, Integer bedId, String date) {
        HealthReportDayVo healthReportDayVo = new HealthReportDayVo();

      /*  Integer bedId = 0;
        if(null != sourceType && sourceType == 2){
            //如果是小程序
            HmpUserBindDevice hmpUserBindDevice = hmpUserBindDeviceService.getOne(Wrappers.<HmpUserBindDevice>lambdaQuery()
                    .eq(HmpUserBindDevice::getUserId, userId).eq(HmpUserBindDevice::getDeviceSn, sn));
            if (hmpUserBindDevice == null) {
                return CommonRes.failed("用户未绑定该设备");
            }
            bedId =hmpUserBindDevice.getBedId();
        }else {
            Radar radar = radarService.getOne(new QueryWrapper<Radar>().lambda().eq(Radar::getSnCode, sn));
            if(Objects.isNull(radar)){
                return CommonRes.failed("该设备号不存在");
            }
            RadarBed radarBed = radarBedService.getOne(new QueryWrapper<RadarBed>().lambda().eq(RadarBed::getRadarId, radar.getId()).eq(RadarBed::getIsDeleted, 0));
            if(Objects.isNull(radarBed)){
                return CommonRes.failed("该设备号未绑定床位");
            }
            bedId = radarBed.getBedId();
        }*/
        //处理前端左右按钮逻辑
        LocalDate localDate = DateTimeUtils.yyyy_MM_dd(date);
        LocalDate now = LocalDate.now().minusDays(1);
        if (now.isBefore(localDate) || now.isEqual(localDate)) {
            healthReportDayVo.setIsRight(false);
        }
        //左边的按钮，需要查询设备的最早报告的日期
        BedHealthDailyStatistics bedHealthDailyStatistics = bedHealthDailyStatisticsService.getOne(new QueryWrapper<BedHealthDailyStatistics>().lambda()
                .eq(BedHealthDailyStatistics::getBedId, bedId).orderByAsc(BedHealthDailyStatistics::getStatisticsDate).last("LIMIT 1"));
        if (!Objects.isNull(bedHealthDailyStatistics)) {
            LocalDate statisticsDate = bedHealthDailyStatistics.getStatisticsDate();//plusday 1
            if (localDate.isBefore(statisticsDate) || localDate.isEqual(statisticsDate)) {
                healthReportDayVo.setIsLeft(false);
            }
        }
        CommonRes<HealthReportOneDayVo> healthReportOneDayVoCommonRes = this.getsleepReportOneDayInfo(userId, null, date, bedId);
        if (healthReportOneDayVoCommonRes.getCode() != 0 || healthReportOneDayVoCommonRes.getData() == null) {
            return CommonRes.failed(healthReportDayVo, healthReportOneDayVoCommonRes.getMsg());
        }

        HealthReportOneDayVo healthReportOneDayVo = healthReportOneDayVoCommonRes.getData();
        SmDetailVo smDetailVo = new SmDetailVo();
        BeanUtils.copyProperties(healthReportOneDayVo, smDetailVo);
        healthReportDayVo.setSmDetail(smDetailVo);
        SmCycleVo smCycleVo = new SmCycleVo();
        BeanUtils.copyProperties(healthReportOneDayVo, smCycleVo);
        healthReportDayVo.setSmCycle(smCycleVo);
        ResRateVo resRateVo = new ResRateVo();
        BeanUtils.copyProperties(healthReportOneDayVo, resRateVo);
        healthReportDayVo.setResRate(resRateVo);
        HeartRateVo heartRateVo = new HeartRateVo();
        BeanUtils.copyProperties(healthReportOneDayVo, heartRateVo);
        healthReportDayVo.setHeartRate(heartRateVo);
        TdDetailVo tdDetailVo = new TdDetailVo();
        BeanUtils.copyProperties(healthReportOneDayVo, tdDetailVo);
        healthReportDayVo.setTdDetail(tdDetailVo);
        SmBreatheVo smBreatheVo = new SmBreatheVo();
        BeanUtils.copyProperties(healthReportOneDayVo, smBreatheVo);
        healthReportDayVo.setSmBreathe(smBreatheVo);
        HxEventVo hxEventVo = new HxEventVo();
        BeanUtils.copyProperties(healthReportOneDayVo, hxEventVo);
        healthReportDayVo.setHxEvent(hxEventVo);
        YcEventVo ycEventVo = new YcEventVo();
        BeanUtils.copyProperties(healthReportOneDayVo, ycEventVo);
        healthReportDayVo.setYcEvent(ycEventVo);
        healthReportDayVo.setFlagBreathReport(healthReportOneDayVo.getFlagBreathReport());
        healthReportDayVo.setBedName(healthReportOneDayVo.getBedName());
        healthReportDayVo.setStatisticsDate(healthReportOneDayVo.getStatisticsDate());
        return CommonRes.ok(healthReportDayVo);
    }


    public CommonRes<HealthReportOneDayVo> getsleepReportOneDayInfo(Long userId, String sn, String date, Integer bedId) {

        HealthReportOneDayVo healthReportOneDayVo = new HealthReportOneDayVo();
        CommonRes<HmpSleepReportBasicVO> sleepReportBasicOneDay = this.getSleepReportBasicOneDay(userId, sn, date, bedId);
        if (sleepReportBasicOneDay.getCode() != 0 || Objects.isNull(sleepReportBasicOneDay.getData())) {
            return CommonRes.failed(sleepReportBasicOneDay.getMsg());
        }
        if (sleepReportBasicOneDay.getCode() == 0 && sleepReportBasicOneDay.getData().getResultFlag() != 0) {
            return CommonRes.failed(sleepReportBasicOneDay.getMsg());
        }
        HmpSleepReportBasicVO data = sleepReportBasicOneDay.getData();
        BeanUtils.copyProperties(data, healthReportOneDayVo);
        healthReportOneDayVo.setSleepScore(data.getScore());
        healthReportOneDayVo.setSleepComment(data.getComment());
        healthReportOneDayVo.setSleepProportion(data.getProportion());
        healthReportOneDayVo.setSleepDuration(getDurationText(data.getSleepDuration()));
        //将睡眠数据转换为map
        Map<String, SleepItemVO> sleepData = data.getSleepInfo().stream().collect(Collectors.toMap(SleepItemVO::getName, Function.identity()));
        List<SleepItemVO> sleepInfo = data.getSleepInfo();
        this.detalSleetData(sleepInfo, sleepData, healthReportOneDayVo);
        //处理活力跌倒等数据
        if (Objects.nonNull(data.getHealthStatus())) {
            this.detalHealthStatus(data, healthReportOneDayVo);
        }
        //获取图标数据
        CommonRes<HmpSleepReportChartVO> sleepReportChartOneDay = this.getSleepReportChartOneDay(userId, sn, date, bedId);
        if (sleepReportChartOneDay.getCode() != 0 || Objects.isNull(sleepReportChartOneDay.getData())) {
            return CommonRes.failed(sleepReportChartOneDay.getMsg());
        }
        HmpSleepReportChartVO hmpSleepReportChartVO = sleepReportChartOneDay.getData();
        BeanUtils.copyProperties(hmpSleepReportChartVO, healthReportOneDayVo);
        //赋值体动时间轴
        this.detalTdData(hmpSleepReportChartVO, data, healthReportOneDayVo);
        //处理睡眠图表时间轴
        this.detalSleepTableList(healthReportOneDayVo, date);
        //处理ahi数据
        this.detalAhiData(healthReportOneDayVo, hmpSleepReportChartVO);
        //处理睡眠呼吸赋值
        this.detalSleepBreathInfo(hmpSleepReportChartVO, healthReportOneDayVo);
        //入睡判断
        if (StringUtils.isNotEmpty(healthReportOneDayVo.getBeginTime()) && DateTimeUtil.compareTime("00:00", healthReportOneDayVo.getBeginTime(), "HH:mm") <= 0
                && DateTimeUtil.compareTime("9:00", healthReportOneDayVo.getBeginTime(), "HH:mm") > 0) {
            healthReportOneDayVo.setIsBeginTime(true);
        }
        ;
        //处理典型呼吸异常事件
        this.detalAbnData(hmpSleepReportChartVO, healthReportOneDayVo);
        //处理心跳呼吸数据
        this.detalBreathData(hmpSleepReportChartVO, healthReportOneDayVo);
        return CommonRes.ok(healthReportOneDayVo);
    }


    private void detalAhiData(HealthReportOneDayVo healthReportOneDayVo, HmpSleepReportChartVO hmpSleepReportChartVO) {
        NumDataItemVO ahiData = hmpSleepReportChartVO.getAhiData();
        List<String> strings = DateTimeUtil.detalStringListToList(hmpSleepReportChartVO.getTimeStampMin());
        ahiData.setXTimeAxis(strings);
        if (!CollectionUtils.isEmpty(ahiData.getData())) {

            List<String> xTimeAxis = ahiData.getXTimeAxis();
            List<Integer> ahiDataList = new ArrayList<>();
            Integer tdNum = 0;
            //TODO 这里算法那边呼吸紊乱两个字段数据处理有问题，要他们那边改，暂时后端先处理一下
            if ("20:00".equals(strings.get(0))) {
                Integer star = 0;
                Integer end = 722;
                if (healthReportOneDayVo.getCutStIdx() != null && healthReportOneDayVo.getCutStIdx() != -1) {
                    star = healthReportOneDayVo.getCutStIdx();
                }
                if (healthReportOneDayVo.getCutEdIdx() != null && healthReportOneDayVo.getCutEdIdx() != -1) {
                    end = healthReportOneDayVo.getCutEdIdx();
                }

                List<String> xTimeAxisList = new ArrayList<>();
                for (int i = 0; i < xTimeAxis.size(); i++) {
                    if (i >= star && i <= end) {
                        xTimeAxisList.add(xTimeAxis.get(i));
                    }
                }
                ahiData.setXTimeAxis(xTimeAxisList);
                //只取时间轴内的呼吸暂停的次数
                for (int i = 0; i < ahiData.getData().size(); i++) {
                    if (i >= star && i <= end) {
                        ahiDataList.add(ahiData.getData().get(i).equals(1) ? 2 : ahiData.getData().get(i));
                    }
                }
            } else {
                for (int i = 0; i < ahiData.getData().size(); i++) {
                    ahiDataList.add(ahiData.getData().get(i).equals(1) ? 2 : ahiData.getData().get(i));
                }
            }
            tdNum = ahiDataList.stream().filter(item -> item == 2).collect(Collectors.toList()).size();
            //赋值体动次数
            ahiData.setNum(tdNum);
            //获取图内的呼吸暂停次数
            ahiData.setData(ahiDataList);
        }
        hmpSleepReportChartVO.setAhiData(ahiData);
    }


    private void detalTdData(HmpSleepReportChartVO hmpSleepReportChartVO, HmpSleepReportBasicVO data, HealthReportOneDayVo healthReportOneDayVo) {

        String bedTime = data.getGetBedTime();
        String leaveTime = data.getLeaveBedTime();
        if ("12:00".equals(healthReportOneDayVo.getBeginTime())) {
            bedTime = "20:00";
        }
        if ("13:00".equals(healthReportOneDayVo.getLeaveBedTime())) {
            leaveTime = "08:00";
        }
        String startTime = DateTimeUtil.detalStringSubTime(bedTime);
        String endTime = DateTimeUtil.detalStringFanTime(leaveTime);
        //处理时间轴
        List<String> timeIntervalAll = DateTimeUtil.getTimeInterval("20:00", "08:00", 15);
        NumDataItemVO turnOverData = hmpSleepReportChartVO.getTurnOverData();
        turnOverData.setXTimeAxis(timeIntervalAll);
        Integer star = 0;
        Integer end = 48;
        if (!CollectionUtils.isEmpty(turnOverData.getData())) {

            for (int i = 0; i < timeIntervalAll.size(); i++) {
                if (timeIntervalAll.get(i).equals(startTime)) {
                    star = i;
                }
                if (timeIntervalAll.get(i).equals(endTime)) {
                    end = i;
                }
            }
            //处理数据
            List<Integer> turnOverDataList = turnOverData.getData();
            List<Integer> turnOverDataNewList = new ArrayList<>();
            for (int i = 0; i < turnOverDataList.size(); i++) {
                if (i >= star && i <= end) {
                    turnOverDataNewList.add(turnOverDataList.get(i));
                }
            }
            turnOverData.setData(turnOverDataNewList);
            List<String> timeInterval = turnOverData.getXTimeAxis();
            List<String> timeIntervalNewList = new ArrayList<>();
            for (int i = 0; i < timeInterval.size(); i++) {
                if (i >= star && i <= end) {
                    timeIntervalNewList.add(timeInterval.get(i));
                }
            }
            turnOverData.setXTimeAxis(timeIntervalNewList);
            Integer max = turnOverDataNewList.stream().max(Comparator.comparingInt(item -> item)).get();
            Integer min = turnOverDataNewList.stream().min(Comparator.comparingInt(item -> item)).get();
            int sum = turnOverDataNewList.stream().mapToInt(item -> item).sum();
            turnOverData.setNum(sum);
            turnOverData.setMax(max);
            turnOverData.setMin(min);
        }
        healthReportOneDayVo.setTurnOverData(turnOverData);
    }

    //处理心跳呼吸数据
    private void detalBreathData(HmpSleepReportChartVO hmpSleepReportChartVO, HealthReportOneDayVo healthReportOneDayVo) {
        BHItemVO heartData = hmpSleepReportChartVO.getHeartData();
        BHItemNewVO bhItemNewVO = new BHItemNewVO();
        BeanUtils.copyProperties(heartData, bhItemNewVO);
        Integer star = 0;
        Integer end = 722;

        if (Objects.nonNull(heartData) && Objects.nonNull(heartData.getData())) {

            if (healthReportOneDayVo.getCutStIdx() != null && healthReportOneDayVo.getCutStIdx() != -1) {
                star = healthReportOneDayVo.getCutStIdx();
            }
            if (healthReportOneDayVo.getCutEdIdx() != null && healthReportOneDayVo.getCutEdIdx() != -1) {
                end = healthReportOneDayVo.getCutEdIdx();
            }
            List<String> heartDataList = new ArrayList<>();
            List<Integer> data = heartData.getData();
            for (int i = 0; i < data.size(); i++) {
                if (i >= star && i <= end && data.get(i) != null) {
                    String heartItem = String.valueOf(data.get(i));
                    if (data.get(i) <= 0) {
                        heartItem = "-";
                    }
                    heartDataList.add(heartItem);
                }
            }

            bhItemNewVO.setData(heartDataList);
        }
        healthReportOneDayVo.setHeartData(bhItemNewVO);


        BHItemVO breathData = hmpSleepReportChartVO.getBreathData();
        BHItemNewVO brItemNewVO = new BHItemNewVO();
        BeanUtils.copyProperties(breathData, brItemNewVO);
        if (Objects.nonNull(breathData) && Objects.nonNull(breathData.getData())) {
            List<String> breathDataList = new ArrayList<>();
            List<Integer> data = breathData.getData();
            for (int i = 0; i < data.size(); i++) {
                if (i >= star && i <= end && data.get(i) != null) {
                    String breathItem = String.valueOf(data.get(i));
                    if (data.get(i) <= 0) {
                        breathItem = "-";
                    }
                    breathDataList.add(breathItem);
                }
            }
            brItemNewVO.setData(breathDataList);
        }
        healthReportOneDayVo.setBreathData(brItemNewVO);
    }

    //处理典型呼吸异常事件
    private void detalAbnData(HmpSleepReportChartVO hmpSleepReportChartVO, HealthReportOneDayVo healthReportOneDayVo) {
        AbnItemVO abnData = healthReportOneDayVo.getAbnData();
        List<AbnBreathPhaseVO> webListFigOssUrl = new ArrayList<>();
        List<AbnBreathPhaseVO> miniListFigOssUrl = new ArrayList<>();
        List<String> breathPhaseSectionTime = new ArrayList<>();
        if (StringUtils.isEmpty(hmpSleepReportChartVO.getFigOssUrl())) {
            return;
        }

        if (StringUtils.isNotEmpty(hmpSleepReportChartVO.getSliceTimeStr())) {
            breathPhaseSectionTime = DateTimeUtil.detalStringListToList(hmpSleepReportChartVO.getSliceTimeStr());
        }

        BreathPhaseListVo breathPhaseListVo = JSONObject.parseObject(hmpSleepReportChartVO.getFigOssUrl(), BreathPhaseListVo.class);
        //web
        List<String> webList = breathPhaseListVo.getWebList();
        if (!CollectionUtils.isEmpty(webList)) {
            for (int i = 0; i < webList.size(); i++) {
                AbnBreathPhaseVO abnBreathPhaseVO = new AbnBreathPhaseVO();
                abnBreathPhaseVO.setWebFigOssUrl(webList.get(i));
                abnBreathPhaseVO.setTime(breathPhaseSectionTime.get(i));
                webListFigOssUrl.add(abnBreathPhaseVO);
            }
        }
        //小程序
        List<String> wxList = breathPhaseListVo.getWxList();
        if (!CollectionUtils.isEmpty(wxList)) {
            for (int i = 0; i < wxList.size(); i++) {
                AbnBreathPhaseVO abnBreathPhaseVO = new AbnBreathPhaseVO();
                abnBreathPhaseVO.setWebFigOssUrl(wxList.get(i));
                abnBreathPhaseVO.setTime(breathPhaseSectionTime.get(i));
                miniListFigOssUrl.add(abnBreathPhaseVO);
            }
        }
        abnData.setWebOssUrlList(webListFigOssUrl);
        abnData.setMiniOssUrlList(miniListFigOssUrl);
        abnData.setSliceNum(webListFigOssUrl.size());
        healthReportOneDayVo.setAbnData(abnData);
    }

    private void detalSleepTableList(HealthReportOneDayVo healthReportOneDayVo, String date) {
        if (StringUtils.isNotEmpty(healthReportOneDayVo.getGetBedTime()) && StringUtils.isNotEmpty(healthReportOneDayVo.getLeaveBedTime())) {
            String startTimeBef = healthReportOneDayVo.getGetBedTime();
            if (healthReportOneDayVo.getGetBedTime().equals("12:00")) {
                startTimeBef = "20:00";
            }
            String endTimeBef = healthReportOneDayVo.getLeaveBedTime();
            if (healthReportOneDayVo.getLeaveBedTime().equals("13:00")) {
                endTimeBef = "08:00";
            }
            Integer star = 0;
            Integer end = 722;
            List<String> minutes = healthReportOneDayVo.getMinutes();
            if (healthReportOneDayVo.getCutStIdx() == null) {
                //第一次循环查找时间轴下坐标
                for (int i = 0; i < minutes.size(); i++) {
                    if (minutes.get(i).equals(startTimeBef)) {
                        star = i;
                    }
                    if (minutes.get(i).equals(endTimeBef)) {
                        end = i;
                    }
                }
                healthReportOneDayVo.setCutStIdx(star);
                healthReportOneDayVo.setCutEdIdx(end);
            } else {
                if (healthReportOneDayVo.getCutStIdx() != null && healthReportOneDayVo.getCutStIdx() != -1) {
                    star = healthReportOneDayVo.getCutStIdx();
                }
                if (healthReportOneDayVo.getCutEdIdx() != null && healthReportOneDayVo.getCutEdIdx() != -1) {
                    end = healthReportOneDayVo.getCutEdIdx();
                }
            }

            String startTime = date + " " + startTimeBef;
            //如果上床时间大于0点小于8点那么就加一天
            if (DateTimeUtil.compareTime("00:00", startTimeBef, "HH:mm") <= 0
                    && DateTimeUtil.compareTime("9:00", startTimeBef, "HH:mm") > 0) {
                startTimeBef = DateTimeUtil.addOneDay(startTime);
            } else {
                startTimeBef = startTime;
            }
            String endTime = date + " " + endTimeBef;
            String addOneDayTime = DateTimeUtil.addOneDay(endTime);
            List<String> hourList = DateTimeUtil.getHourList(startTimeBef, addOneDayTime);
            healthReportOneDayVo.setSleepTableTimeList(hourList);

            List<String> minutesNewList = new ArrayList<>();
            for (int i = 0; i < minutes.size(); i++) {
                if (i >= star && i <= end) {
                    minutesNewList.add(minutes.get(i));
                }
            }
            healthReportOneDayVo.setMinutes(minutesNewList);
            //处理睡眠横轴数据
            List<SleepDataVO> sleepData = healthReportOneDayVo.getSleepData();
            if (!CollectionUtils.isEmpty(sleepData)) {
                for (SleepDataVO sleepDatum : sleepData) {
                    List<String> sleepDataNew = new ArrayList<>();
                    for (int i = 0; i < sleepDatum.getDatas().size(); i++) {
                        if (i >= star && i <= end) {
                            sleepDataNew.add(sleepDatum.getDatas().get(i));
                        }
                    }
                    sleepDatum.setDatas(sleepDataNew);
                }
            }
        }
        if ("12:00".equals(healthReportOneDayVo.getGetBedTime())) {
            healthReportOneDayVo.setGetBedTime("20:00前");
        }
        if ("12:00".equals(healthReportOneDayVo.getBeginTime())) {
            healthReportOneDayVo.setBeginTime("20:00前");
        }
        if ("13:00".equals(healthReportOneDayVo.getEndTime())) {
            healthReportOneDayVo.setEndTime("08:00后");
        }
        if ("13:00".equals(healthReportOneDayVo.getLeaveBedTime())) {
            healthReportOneDayVo.setLeaveBedTime("08:00后");
        }
    }

    private void detalSleepBreathInfo(HmpSleepReportChartVO hmpSleepReportChartVO, HealthReportOneDayVo healthReportOneDayVo) {
        List<BreathEventVO> healthReport = hmpSleepReportChartVO.getHealthReport();
        if (CollectionUtils.isEmpty(healthReport)) {
            return;
        }
        Map<String, BreathEventVO> breathEventVOMap = healthReport.stream().collect(Collectors.toMap(BreathEventVO::getName, Function.identity()));
        if (breathEventVOMap.containsKey("呼吸暂停")) {
            BreathEventVO breathEventVO = new BreathEventVO();
            breathEventVO.setName(breathEventVOMap.get("呼吸暂停").getName());
//            breathEventVO.setValue(breathEventVOMap.get("呼吸暂停").getValue());
            breathEventVO.setValue(hmpSleepReportChartVO.getAhiData().getNum()); //这里取上面获取的时间轴内的呼吸暂停次数
            breathEventVO.setAverageDuration(breathEventVOMap.get("呼吸暂停").getAverageDuration());
            //睡眠呼吸暂停情况
            healthReportOneDayVo.setSleepBreathStop(breathEventVO);
        }
        if (breathEventVOMap.containsKey("AHI")) {
            BreathEventVO breathEventVO = new BreathEventVO();
            breathEventVO.setName(breathEventVOMap.get("AHI").getName());
            breathEventVO.setValue(breathEventVOMap.get("AHI").getValue());
            breathEventVO.setAverageDuration(breathEventVOMap.get("AHI").getAverageDuration());
            //呼吸紊乱情况
            healthReportOneDayVo.setBreathDisorder(breathEventVO);
        }
    }

    private void detalHealthStatus(HmpSleepReportBasicVO data, HealthReportOneDayVo healthReportOneDayVo) {
        if (null != data.getHealthStatus().getVitality()) {
            HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
            healthReportSleepVO.setName("活力指数");
            healthReportSleepVO.setValue(data.getHealthStatus().getVitality().toString());
            healthReportSleepVO.setComment(data.getGradeMap().get("vitality").toString());
            healthReportOneDayVo.setVitality(healthReportSleepVO);
        }
        if (null != data.getHealthStatus().getMorale()) {
            HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
            healthReportSleepVO.setName("情绪指数");
            healthReportSleepVO.setValue(data.getHealthStatus().getMorale().toString());
            healthReportSleepVO.setComment(data.getGradeMap().get("morale").toString());
            healthReportOneDayVo.setMorale(healthReportSleepVO);
        }
        if (null != data.getHealthStatus().getFall()) {
            HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
            healthReportSleepVO.setName("跌倒指数");
            healthReportSleepVO.setValue(data.getHealthStatus().getFall().toString());
            healthReportSleepVO.setComment(data.getGradeMap().get("fall").toString());
            healthReportOneDayVo.setFall(healthReportSleepVO);
        }
    }

    private void detalSleetData(List<SleepItemVO> sleepInfo, Map<String, SleepItemVO> sleepData, HealthReportOneDayVo healthReportOneDayVo) {
        //睡眠数据处理
        if (!CollectionUtils.isEmpty(sleepInfo)) {

            if (sleepData.containsKey("睡眠时长")) {
                HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
                BeanUtils.copyProperties(sleepData.get("睡眠时长"), healthReportSleepVO);
                healthReportOneDayVo.setSleepLenValidMin(healthReportSleepVO);
            }
            if (sleepData.containsKey("深睡时长")) {
                HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
                BeanUtils.copyProperties(sleepData.get("深睡时长"), healthReportSleepVO);
                healthReportOneDayVo.setDeepSleepDuration(healthReportSleepVO);
            }
            if (sleepData.containsKey("浅睡时长")) {
                HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
                BeanUtils.copyProperties(sleepData.get("浅睡时长"), healthReportSleepVO);
                healthReportOneDayVo.setLightSleepDuration(healthReportSleepVO);
            }
            if (sleepData.containsKey("清醒时长")) {
                HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
                BeanUtils.copyProperties(sleepData.get("清醒时长"), healthReportSleepVO);
                healthReportOneDayVo.setClearSleepDuration(healthReportSleepVO);
            }

            if (sleepData.containsKey("离床时长")) {
                HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
                BeanUtils.copyProperties(sleepData.get("离床时长"), healthReportSleepVO);
                healthReportOneDayVo.setOutBedDuration(healthReportSleepVO);
            }

            if (sleepData.containsKey("离床次数")) {
                HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
                BeanUtils.copyProperties(sleepData.get("离床次数"), healthReportSleepVO);
                healthReportOneDayVo.setOutBedNum(healthReportSleepVO);
            }

            if (sleepData.containsKey("体动次数")) {
                HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
                BeanUtils.copyProperties(sleepData.get("体动次数"), healthReportSleepVO);
                healthReportOneDayVo.setTurnOverNum(healthReportSleepVO);
            }
            if (sleepData.containsKey("睡眠效率")) {
                HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
                BeanUtils.copyProperties(sleepData.get("睡眠效率"), healthReportSleepVO);
                healthReportOneDayVo.setSleepEfficiency(healthReportSleepVO);
            }

            if (sleepData.containsKey("睡眠呼吸")) {
                HealthReportSleepVO healthReportSleepVO = new HealthReportSleepVO();
                BeanUtils.copyProperties(sleepData.get("睡眠呼吸"), healthReportSleepVO);
                healthReportOneDayVo.setSleepBreath(healthReportSleepVO);
            }

        }
    }

    /**
     * 转换时长文本
     *
     * @param duration
     * @return
     */
    private static String getDurationText(Integer duration) {
        Integer hour = duration / 60;
        Integer minute = duration % 60;
        StringBuilder sb = new StringBuilder();
        if (hour > 0) {
            sb.append(hour);
            sb.append("小时");
        }
        sb.append(minute);
        sb.append("分钟");
        return sb.toString();
    }


}
